/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.pb.diplom.first.business;

import com.pb.diplom.first.dao.CommodityJoinDao;
import com.pb.diplom.first.dbProp.DbProperties;
import com.pb.diplom.first.tables.Commodity;
import com.pb.diplom.first.tables.CommodityJoin;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import java.sql.SQLException;
import java.util.Collection;

/**
 *
 * @author Slava
 */
public class DBStorageCommodity {

    private final static DBStorageCommodity instance = new DBStorageCommodity();
    private final Map<Long, CommodityJoin> commodity = new HashMap<>();
    CommodityJoin categories = new CommodityJoin();
    private Long uniqueIndex = 0L;
    CommodityJoinDao dao = new CommodityJoinDao(DbProperties.LOGIN, DbProperties.PASSWORD, DbProperties.URL);

    private DBStorageCommodity() {
        init();
    }

    public static DBStorageCommodity getInstance() {
        return instance;
    }

    //long id, long producerId, long categoryId, String model, BigDecimal price, String description, String image, String storage
    private void init() {
        List<CommodityJoin> comm = dao.getAll();
        for (CommodityJoin commodity : comm) {
            this.commodity.put(commodity.getId(), new CommodityJoin(commodity.getModel(), commodity.getNameManufacturer(), commodity.getNameCategory(), commodity.getDescription(), commodity.getPrice(), commodity.getStorage()));
        }
    }

    public CommodityJoin saveOrUpdate(CommodityJoin commodity) throws SQLException {
        dao.save(commodity);
        //sleep(1000);
        CommodityJoin item = commodity.getId() != null
                ? commodity : new CommodityJoin();
        return item;
    }

    public Collection<CommodityJoin> getCommodities() {
        return commodity.values();
    }

    public Object[][] getCommoditiesAsTable() throws SQLException {
        Object[][] result = new Object[commodity.size()][6];
        int index = 0;
        for (CommodityJoin cat : dao.getAll()) {

            result[index][0] = cat.getModel();
            result[index][1] = cat.getNameManufacturer();
            result[index][2] = cat.getNameCategory();
            result[index][3] = cat.getDescription();
            result[index][4] = cat.getPrice();
            result[index][5] = cat.getStorage();
            index++;
        }
        return result;
    }

}
